import { Component, Input, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { ApesModalRef, ApesModalService } from '@shared/apes/modal';
import { deepClone, replaceAll } from '../../utils/utils';
import { UserAuthService } from '@core/services/user-auth.service';
import { FormGroup } from '@angular/forms';
import { ApesPreviewDialogComponent } from '@shared/ag-grid-ext/upload-component/apes-previewDialog.component';
import { ApesUploadDialogComponent } from '@shared/ag-grid-ext/upload-component';


@Component({
  selector: 'dialog-make-inquiry',
  templateUrl: './dialog-make-inquiry.component.html',
})
export class DialogMakeInquiryComponent implements OnInit {
  model: any = {};
  options: any;
  resultsData: any = [];
  resultData: any;

  body: any = {};

  @Input() conditionModel: any;
  @Input() gridData: any;
  @Input() api: any = 'fn.priceForwardService.mergeResult';

  id: string;                               // 方案号
  sign: boolean = true;                            // 勾选标记

  isLoading: boolean = false;
  tabSetIndex: any = 0;
  inquiryInitData: any = {};
  inquiryLeftData: any[] = [];
  inquiryRightData: any[] = [];
  inquiryShowData: any[] = [];
  postTotal: any = 0;

  total: any = 0;

  inquiryTotal: any = 0;
  quoted: any = 0;
  showHidden: boolean = false;
  multiple: boolean = true;

  filterField: any = [
    { type: 'categoryName', name: '配件' }, // 配件 PJMC
    { type: 'ZDMC', name: '送达站点' }, // 送达站点
    { type: 'qualityName', name: '品质' }, // 品质  PZMC
    { type: 'supplier', name: '供应商代码' }, // 供应商
  ];

  showInquiry: boolean = false;
  selectAllCategoryName: boolean = false;


  constructor(private apiService: ApiService,
              protected userService: UserAuthService,
              private modalService: ApesModalService,
              private msg: ApesMessageService,
              public modal: ApesModalRef) {

  }

  ngOnInit() {
    this.resetMakeInquiry();
  }


  resetMakeInquiry() {
    let api = this.api;
    let setData = deepClone(this.conditionModel);
    let platform = this.userService.getUserInfoObj() ? this.userService.getUserInfoObj().platform : '';
    const data = { ...setData, platform: platform };
    this.isLoading = true;
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        console.log('配件数据--', body);
        if (body) {
          this.inquiryInitData['enquiryID'] = body['enquiryID'];
          this.inquiryInitData['CLXX'] = body['CLXX'];

          if (body.hasOwnProperty('sign')) {
            this.sign = !!body['sign'];
            // this.resultData = {};
          }

          this.inquiryLeftData = body['results'];
          this.inquiryRightData = this.filtrationSelect(body['results']);
          this.inquiryShowData = deepClone(this.inquiryRightData);
          this.filterCondition();
          this.postTotal = 0;
          // if (this.conditionModel.hasOwnProperty('node')) {
          this.checkFiltrationData();
          // }
          this.getTotal();
        }
        this.isLoading = false;
        this.onSelectionChanged(this.inquiryRightData);
      });
  }

  filtrationSelect(params) {
    let param = deepClone(params);
    param.forEach((com) => {
      com.item.forEach((list) => {
        let selectFlag = 0;
        if (list.hasOwnProperty('WYZ')) {
          let gridData;
          if (this.conditionModel.formId == 'crm.servicePlan') {
            let workItems = this.conditionModel.workItems;
            let fittingsItems = this.conditionModel.fittingsItems;
            gridData = deepClone([...workItems, ...fittingsItems]);
          } else {
            gridData = deepClone(this.gridData);
          }
          if (gridData) {
            gridData.forEach((data) => {
              if (data.hasOwnProperty('uniqueValue') && data['uniqueValue'] == list['WYZ']) {
                selectFlag = 1;
                list['refactorData'] = deepClone(data);
                if (list['refactorData'].hasOwnProperty('logisticsMode')) {
                  list['logisticsMode'] = list['refactorData']['logisticsMode'];
                }
              }
            });
          }
        } else {
          selectFlag = 0;
        }
        list.selectFlag = selectFlag;
        if (!list['logisticsModeItems']) {
          list['logisticsLoading'] = false;
          if (list['logisticsMode']) {
            list['logisticsModeItems'] = [...list['logisticsMode']];
          } else {
            list['logisticsModeItems'] = [];
          }
        }
      });
    });
    return param;
  }

  logisticsModeChange(e, param) {
    console.log(param);
  }

  checkLogisticsMode(param) {
    let item = param['logisticsModeItems'];
    if (item.length <= 1) {
      param['logisticsLoading'] = true;
      let api = 'fn.servicePlanceService.queryCarrierFrom';
      let setData = {
        'EXTERNAL_GYSID': param['EXTERNAL_GYSID'],
        'MDID': param['MDID'],
      };
      this.apiService.post(api, setData).subscribe((body) => {
        console.log(body);
        param['logisticsLoading'] = false;
        param['logisticsModeItems'] = body;
      });
    }
  }

  filterCondition() {

    this.filterField.forEach((field) => {
      field.data = [];
      field.data = this.filtrationData(field.type);
    });
  }

  filtrationData(type) {
    let showData = [];
    let list = deepClone(this.inquiryLeftData);
    let node = deepClone(this.conditionModel.node);
    list.forEach((data, index) => {
      data.item.forEach((res) => {
        let check = true;
        showData.forEach((sd) => {
          if (sd[type] == res[type]) {
            check = false;
          }
        });
        if (check) {
          let checked = true;
          if (type == 'categoryName') {
            if (node && this.sign) {
              if (res[type] == node['category']['name']) {
                checked = true;
              } else {
                checked = false;
              }
            } else if (index != 0) {
              checked = false;
            }
          }

          showData.push({ [type]: res[type], checked: checked });
        }
      });
    });
    return showData;
  }

  checkFiltrationData() {
    // console.log(this.filterField);
    let show = true;
    let list = deepClone(this.inquiryRightData);
    list.forEach((data) => {
      data.item = data.item.filter((item) => {
        return this.filter(item);
      });
      if (data.item.length != 0) {
        show = false;
      }
    });
    this.inquiryShowData = list;
    this.showInquiry = show;
    this.checkSelectAll();
  }

  checkSelectAll() {
    let check = true;
    this.filterField.forEach((field) => {
      if (field.type == 'categoryName') {
        field.data.forEach((data) => {
          if (!data.checked) {
            check = false;
          }
        });
      }
    });
    this.selectAllCategoryName = check;
  }

  selectAll() {
    let selectAll = this.selectAllCategoryName;
    this.filterField.forEach((field) => {
      if (field.type == 'categoryName') {
        field.data.forEach((data) => {
          data.checked = selectAll;
        });
      }
    });
    this.checkFiltrationData();
  }

  filter(filterData) {
    let check = true;
    this.filterField.forEach((field) => {
      let type = field.type;
      field.data.forEach((data) => {
        if (data[type] == filterData[type] && check != false) {
          check = data.checked;
        }
      });
    });
    return check;
  }

  checkSelectSum(data) {
    let resultsData = this.inquiryRightData;
    let sum = 0;
    if (resultsData.length != 0) {
      resultsData.forEach((res) => {
        if (data == res['categoryName']) {
          if (res.item.length == 0) return;
          res.item.forEach((r) => {
            if (r.selectFlag == 1) {
              sum += 1;
            }
          });
        }
      });
    }
    return sum;
  }

  selectProduct(data, list) {
    if (!data.logisticsMode && data.selectFlag == 0) {
      return this.msg.error('请选择对应物流方式！');
    }
    data.selectFlag = data.selectFlag == 0 ? 1 : 0;

    // 用于控制只能选一个
    // if (data.selectFlag == 1) {
    //   list.item.forEach((li) => {
    //     if (data.WYZ != li.WYZ && data.SPID == li.SPID) {
    //       li.selectFlag = 0;
    //     }
    //   });
    // }

    this.inquiryRightData.forEach((res) => {
      if (res.YSPID == list.YSPID) {
        res.item.forEach((re) => {
          if (re.SPID == data.SPID && re.WYZ == data.WYZ) {
            if (data.selectFlag == 1) {
              re.selectFlag = data.selectFlag;
              re['logisticsMode'] = data['logisticsMode'];
              if (!re.hasOwnProperty('refactorData') || re.refactorData == undefined) {
                this.postTotal = this.postTotal + 1;
                this.resultsData = [];

                if (re.ssign == '00') {
                  this.getInquiryPoolItem(re, (reData) => {
                    re['refactorData'] = reData;
                    this.postTotal = this.postTotal - 1;
                    if (this.postTotal == 0) {
                      this.onSelectionChanged(this.inquiryRightData);
                    }
                  });
                } else {
                  this.getInquiryQuotationItem(re, (reData) => {
                    re['refactorData'] = reData;
                    this.postTotal = this.postTotal - 1;
                    if (this.postTotal == 0) {
                      this.onSelectionChanged(this.inquiryRightData);
                    }
                  });
                }
              } else {
                if (re.refactorData.hasOwnProperty('logisticsMode')) {
                  re.refactorData['logisticsMode'] = data['logisticsMode'];
                }
              }
            } else {
              re.selectFlag = 0;
            }
          }
        });
      }
    });

    if (this.postTotal == 0) {
      this.onSelectionChanged(this.inquiryRightData);
    }
  }

  showPhoto(param) {

    let value = deepClone(param);
    if (value) {
      value = replaceAll(value, '\"', '"');
    }
    let dialog: any = ApesPreviewDialogComponent;
    let fileList = JSON.parse(value) || [];
    let option = {
      title: '预览图片',
      _fileList: fileList,
    };

    this.openUploadDialog(option, (result: any) => {
    }, dialog);
  }

  openUploadDialog(option: any, callback: any, dialog?: any) {

    let body: any = { ...option };
    const openDialog = dialog ? dialog : ApesUploadDialogComponent;
    const dialogRef = this.modalService.create({
      apesWidth: '45vw',
      apesTitle: body.title,
      apesContent: openDialog,
      apesComponentParams: body,
      apesFooter: [
        {
          label: '取消',
          type: 'default',
          onClick: (componentInstance) => {
            dialogRef.destroy(componentInstance['fileList']);
            // dialogRef.close();
          },
        },
        {
          label: '确定',
          type: 'primary',
          disabled: (componentInstance) => {
            return componentInstance['uploading'];
          },
          onClick: (componentInstance) => {
            // console.log(componentInstance);
            dialogRef.destroy(componentInstance['fileList']);
          },
        },
      ],
    });

    return dialogRef.afterClose.subscribe((result) => callback(result));
  }

  showBadges(param) {
    let num = 0;
    let value = deepClone(param);
    if (value) {
      value = replaceAll(value, '\"', '"');
      num = JSON.parse(value).length;
    }
    return num;
  }

  getInquiryPoolItem(data, callBack) {
    let api = 'fn.service.getInquiryPoolItem';
    let setData = { 'PUR_SPXJDMX': [data], ...this.conditionModel };

    this.apiService.post(api, { 'body': JSON.stringify(setData) }).subscribe(
      (body) => {
        // console.log(body);
        if (body) {
          callBack(body[0]);
        }
      });
  }

  getInquiryQuotationItem(data, callBack) {
    let api = 'fn.priceForwardService.oneInputServicePlanItem';
    let setData = { 'data': data, model: this.conditionModel };

    this.apiService.post(api, { 'body': JSON.stringify(setData) }).subscribe(
      (body) => {
        // console.log(body);
        if (body) {
          callBack(body);
        }
      });
  }

  onSelectionChanged(selectedRow) {

    const data = [];
    selectedRow.forEach((list) => {
      list.item.forEach((item) => {
        if (item.selectFlag == 1) {
          data.push(item['refactorData']);
        }
      });
    });
    this.resultsData = data;
    this.getTotal();
  }

  getTotal() {
    let total = 0;
    this.inquiryRightData.forEach((list) => {
      list.item.forEach((item) => {
        if (item.selectFlag == 1) {
          total += 1;
        }
      });
    });
    this.total = total;
  }

  destroyModal(): void {
    this.modal.destroy(this.resultsData);
  }

  openShowHidden() {
    this.showHidden = !this.showHidden;
  }

  resetCondition() {
    this.tabSetIndex = 0;
    this.filterField.forEach((field) => {
      field.data.forEach((data) => {
        data.checked = true;
      });
    });
    this.inquiryShowData = deepClone(this.inquiryRightData);
    this.showInquiry = false;
  }

}
